Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make nft web app nicer #602

Merged
merged 2 commits into from
Dec 13, 2024
Merged

Make nft web app nicer #602

merged 2 commits into from
Dec 13, 2024

Conversation

kongzii
Copy link
Contributor

@kongzii kongzii commented Dec 13, 2024

A few changes:

  • background switching between messages
  • reasoning not shown as function calls
  • Function Call + Function Response merged into a single message

Screenshot by Dropbox Capture

Copy link
Contributor

coderabbitai bot commented Dec 13, 2024

Walkthrough

The pull request introduces several modifications across three files, primarily focusing on the handling of messages and the structure of function calls in app_nft_treasury_game.py. The parse_function_and_body function's parameters and return type have been simplified by removing the "system" role. The customized_chat_message function has been restructured to accept function_call and function_output parameters, enhancing message clarity. Additionally, the return types of the search method in LongTermMemoryTableHandler and the get_with_filter_and_order method in SQLHandler have been updated to return lists instead of sequences.

Changes

File Change Summary
prediction_market_agent/agents/microchain_agent/nft_treasury_game/app_nft_treasury_game.py - Updated parse_function_and_body to remove "system" role, changing its parameters and return type.
- Modified customized_chat_message to accept function_call and function_output, adjusting internal logic for message handling.
- Altered show_function_calls_part to filter out system calls from displayed messages.
- Updated import statements to include new dependencies.
prediction_market_agent/db/long_term_memory_table_handler.py - Changed return type of search method from t.Sequence[LongTermMemories] to list[LongTermMemories].
prediction_market_agent/db/sql_handler.py - Changed return type of get_with_filter_and_order method from t.Sequence[SQLModelType] to list[SQLModelType].

Possibly related PRs

  • Tavily storage #381: The changes in app_nft_treasury_game.py involve the handling of messages, which may relate to the message handling improvements introduced in messages_functions.py in PR Tavily storage #381, particularly with the introduction of new message functions.
  • Sending messages from general agent #581: The modifications in messages_functions.py in this PR include the introduction of new classes for sending messages, which aligns with the changes in message handling in the main PR.
  • NFT functions for general agent #582: The addition of NFT-related functionalities in messages_functions.py and the introduction of new classes for handling NFT operations are relevant to the changes in message handling and processing in the main PR.

Suggested reviewers

  • evangriffiths

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@kongzii kongzii mentioned this pull request Dec 13, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (1)
prediction_market_agent/agents/microchain_agent/nft_treasury_game/app_nft_treasury_game.py (1)

146-149: Re-evaluate the necessity of filtering "system" roles

Since the "system" role has been removed from handling in parse_function_and_body, consider whether filtering out "system" roles in this context remains necessary. Removing redundant code can improve maintainability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1b45fbd and cdaa11e.

📒 Files selected for processing (3)
  • prediction_market_agent/agents/microchain_agent/nft_treasury_game/app_nft_treasury_game.py (6 hunks)
  • prediction_market_agent/db/long_term_memory_table_handler.py (1 hunks)
  • prediction_market_agent/db/sql_handler.py (1 hunks)
🔇 Additional comments (4)
prediction_market_agent/agents/microchain_agent/nft_treasury_game/app_nft_treasury_game.py (2)

14-14: Import of check_not_none looks appropriate

The addition of check_not_none import aligns with its usage in the code.


31-33: Importing LongTermMemories and LongTermMemoryTableHandler

The imported classes are used later in the code, ensuring that dependencies are correctly managed.

prediction_market_agent/db/sql_handler.py (1)

38-38: Update type hint to list[SQLModelType] for consistency

Changing the return type from t.Sequence[SQLModelType] to list[SQLModelType] clarifies the expected return type and aligns with Python's type hinting conventions.

prediction_market_agent/db/long_term_memory_table_handler.py (1)

52-52: Update return type to list[LongTermMemories] for clarity

Modifying the return type of search to return a list enhances type consistency and clarity across the codebase.

Comment on lines +87 to +99
function_call: LongTermMemories,
function_output: LongTermMemories,
) -> None:
parsed_function, parsed_body = parse_function_and_body(role, message)
if parsed_function is None:
return
# If the message is output from one of these functions, skip it, because it's not interesting to read `The reasoning has been recorded` and similar over and over again.
if parsed_body in (
Reasoning()(""),
BroadcastPublicMessageToHumans.OUTPUT_TEXT,
SendPaidMessageToAnotherAgent.OUTPUT_TEXT,
):
return
created_at = function_output.datetime_

parsed_function_call_name, parsed_function_call_body = parse_function_and_body(
check_not_none(function_call.metadata_dict)["role"],
check_not_none(function_call.metadata_dict)["content"],
)
parsed_function_output_name, parsed_function_output_body = parse_function_and_body(
check_not_none(function_output.metadata_dict)["role"],
check_not_none(function_output.metadata_dict)["content"],
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle potential KeyError when accessing metadata_dict keys

Accessing metadata_dict["role"] and metadata_dict["content"] without checking if the keys exist may lead to a KeyError. Consider using the .get() method with default values or adding error handling to ensure robustness.

Apply this diff to prevent potential KeyError exceptions:

 parsed_function_call_name, parsed_function_call_body = parse_function_and_body(
-    check_not_none(function_call.metadata_dict)["role"],
-    check_not_none(function_call.metadata_dict)["content"],
+    check_not_none(function_call.metadata_dict.get("role", "")),
+    check_not_none(function_call.metadata_dict.get("content", "")),
 )

 parsed_function_output_name, parsed_function_output_body = parse_function_and_body(
-    check_not_none(function_output.metadata_dict)["role"],
-    check_not_none(function_output.metadata_dict)["content"],
+    check_not_none(function_output.metadata_dict.get("role", "")),
+    check_not_none(function_output.metadata_dict.get("content", "")),
 )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function_call: LongTermMemories,
function_output: LongTermMemories,
) -> None:
parsed_function, parsed_body = parse_function_and_body(role, message)
if parsed_function is None:
return
# If the message is output from one of these functions, skip it, because it's not interesting to read `The reasoning has been recorded` and similar over and over again.
if parsed_body in (
Reasoning()(""),
BroadcastPublicMessageToHumans.OUTPUT_TEXT,
SendPaidMessageToAnotherAgent.OUTPUT_TEXT,
):
return
created_at = function_output.datetime_
parsed_function_call_name, parsed_function_call_body = parse_function_and_body(
check_not_none(function_call.metadata_dict)["role"],
check_not_none(function_call.metadata_dict)["content"],
)
parsed_function_output_name, parsed_function_output_body = parse_function_and_body(
check_not_none(function_output.metadata_dict)["role"],
check_not_none(function_output.metadata_dict)["content"],
)
function_call: LongTermMemories,
function_output: LongTermMemories,
) -> None:
created_at = function_output.datetime_
parsed_function_call_name, parsed_function_call_body = parse_function_and_body(
check_not_none(function_call.metadata_dict.get("role", "")),
check_not_none(function_call.metadata_dict.get("content", "")),
)
parsed_function_output_name, parsed_function_output_body = parse_function_and_body(
check_not_none(function_output.metadata_dict.get("role", "")),
check_not_none(function_output.metadata_dict.get("content", "")),
)

Comment on lines 114 to 119
if parsed_function_call_name == Reasoning.__name__:
# Don't show reasoning as function call, to make it a bit nicer.
st.markdown(
parsed_function_call_body.replace("reasoning='", "").replace("')", "")
)
else:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve parsing of parsed_function_call_body for robustness

Using string replacements to parse parsed_function_call_body may not handle all cases correctly. Consider using regular expressions or parsing the arguments properly to make the code more robust.

Apply this diff to use a regular expression for parsing:

+import re
...
     if parsed_function_call_name == Reasoning.__name__:
         # Don't show reasoning as function call, to make it a bit nicer.
-        st.markdown(
-            parsed_function_call_body.replace("reasoning='", "").replace("')", "")
-        )
+        reasoning_match = re.match(r"reasoning=['"](.*)['"]", parsed_function_call_body)
+        if reasoning_match:
+            reasoning_text = reasoning_match.group(1)
+            st.markdown(reasoning_text)
+        else:
+            st.markdown(parsed_function_call_body)

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +68 to +69
role: t.Literal["user", "assistant"], message: str
) -> t.Tuple[str, str]:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Based on the gathered evidence, I can now provide a final response:

The "system" role removal requires attention in specific files

The codebase still contains several references to the "system" role that need to be addressed:

  • prediction_market_agent/agents/microchain_agent/agent_functions.py: Uses "system" role in history assignment
  • prediction_market_agent/agents/microchain_agent/microchain_agent.py: Contains two instances of "system" role usage
  • prediction_market_agent/agents/microchain_agent/memory.py: Has a comparison with "system" role
  • prediction_market_agent/agents/microchain_agent/nft_treasury_game/app_nft_treasury_game.py: Contains filtering logic for "system" role

While the parse_function_and_body function has been updated to exclude the "system" role, there are still active uses of it in the codebase that need to be reviewed and potentially updated for consistency.

🔗 Analysis chain

Confirm removal of the "system" role throughout the codebase

The parse_function_and_body function now excludes the "system" role. Please verify that all references to the "system" role have been updated elsewhere to prevent potential inconsistencies or errors.

Run the following script to check for any remaining references to the "system" role:


Let me gather more context about the usage of roles in the codebase, particularly around the parse_function_and_body function.


Let me try a different approach to understand the context better.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for references to the "system" role in the codebase.

# Test: Find occurrences where "role" is assigned or compared to "system"
rg 'role.*["'\'']system["'\'']'

Length of output: 1616


Script:

#!/bin/bash
# Check the implementation of parse_function_and_body and surrounding context
ast-grep --pattern 'def parse_function_and_body($$$) {
  $$$
}'

# Also check for any type definitions or constants related to roles
rg -A 3 'Literal\[.*"system".*\]|ROLE_.*system'

Length of output: 115


Script:

#!/bin/bash
# Get the full content of the file containing parse_function_and_body
fd "app_nft_treasury_game.py" --exec cat {}

# Look for any role-related type definitions or enums
rg "Literal\[.*role.*\]|Role|ROLE"

Length of output: 10233

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
prediction_market_agent/agents/microchain_agent/nft_treasury_game/app_nft_treasury_game.py (1)

153-154: Reevaluate the necessity of filtering out 'system' roles

Since 'system' roles are being removed from message handling, verify if filtering out 'system' roles is still necessary. If 'system' roles are no longer present in the metadata_dict, you may remove this filter to simplify the code.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cdaa11e and f58818d.

📒 Files selected for processing (1)
  • prediction_market_agent/agents/microchain_agent/nft_treasury_game/app_nft_treasury_game.py (6 hunks)
🔇 Additional comments (4)
prediction_market_agent/agents/microchain_agent/nft_treasury_game/app_nft_treasury_game.py (4)

93-99: Handle potential KeyError when accessing metadata_dict keys

Accessing metadata_dict["role"] and metadata_dict["content"] without checking for key existence may lead to a KeyError. Consider using the .get() method with default values or adding error handling to ensure robustness.

Apply this diff to prevent potential KeyError exceptions:

 parsed_function_call_name, parsed_function_call_body = parse_function_and_body(
-    check_not_none(function_call.metadata_dict)["role"],
-    check_not_none(function_call.metadata_dict)["content"],
+    check_not_none(function_call.metadata_dict.get("role", "")),
+    check_not_none(function_call.metadata_dict.get("content", "")),
 )

 parsed_function_output_name, parsed_function_output_body = parse_function_and_body(
-    check_not_none(function_output.metadata_dict)["role"],
-    check_not_none(function_output.metadata_dict)["content"],
+    check_not_none(function_output.metadata_dict.get("role", "")),
+    check_not_none(function_output.metadata_dict.get("content", "")),
 )

116-120: Improve parsing of parsed_function_call_body for robustness

Using string replacements to parse parsed_function_call_body may not handle all cases correctly. Consider using regular expressions or proper argument parsing to enhance robustness.

Apply this diff to use a regular expression for parsing:

+import re
...
     if parsed_function_call_name == Reasoning.__name__:
         # Don't show reasoning as function call to make it nicer.
-        st.markdown(
-            parsed_function_call_body.replace("reasoning='", "").replace("')", "")
-        )
+        reasoning_match = re.match(r"reasoning=['\"](.*)['\"]", parsed_function_call_body)
+        if reasoning_match:
+            reasoning_text = reasoning_match.group(1)
+            st.markdown(reasoning_text)
+        else:
+            st.markdown(parsed_function_call_body)

153-154: ⚠️ Potential issue

Handle potential KeyError when filtering calls based on metadata_dict["role"]

When filtering calls, accessing metadata_dict["role"] without checking for key existence may lead to a KeyError. Consider using the .get() method with a default value or adding error handling.

Apply this diff to prevent potential KeyError exceptions:

 calls = [
-    call for call in calls if check_not_none(call.metadata_dict)["role"] != "system"
+    call for call in calls if check_not_none(call.metadata_dict.get("role", "")) != "system"
 ]

Likely invalid or redundant comment.


68-69: Ensure all calls to parse_function_and_body use valid role values

The parse_function_and_body function now accepts role as Literal["user", "assistant"]. Please verify that there are no calls passing 'system' as the role argument. Any such calls will raise a ValueError.

Run the following script to identify any calls with 'system' as role:

✅ Verification successful

No issues with parse_function_and_body role usage

The codebase explicitly filters out messages with role="system" before they reach parse_function_and_body. This is evident from:

  1. The filtering in microchain_agent.py that excludes system messages from history
  2. The explicit filtering in app_nft_treasury_game.py that removes system messages from calls
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find calls to parse_function_and_body with 'system' as the role argument.

# Search for function calls to parse_function_and_body where role is 'system'
rg -A 2 'parse_function_and_body\(' -g "*.py" | grep -E 'role\s*=\s*["'\'']system["'\'']'

Length of output: 91


Script:

#!/bin/bash
# Let's first find all calls to parse_function_and_body to analyze their role arguments
rg -A 3 'parse_function_and_body\(' -g "*.py"

Length of output: 1718


Script:

#!/bin/bash
# Let's examine the metadata_dict to see what roles are being passed
rg -B 3 -A 1 'metadata_dict.*role' -g "*.py"

Length of output: 2627

@kongzii kongzii merged commit b670cfe into main Dec 13, 2024
10 checks passed
@kongzii kongzii deleted the peter/prettier-nft branch December 13, 2024 14:18
@coderabbitai coderabbitai bot mentioned this pull request Dec 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants